import Logger from "../utils/Logger";
import { delay } from "../utils/utils";
import { AxiosManager, GameMessage, getCurrentSession } from "./AxiosManager";

/**
 * 通用目的的心跳请求。无特殊情况时，服务器不会发回对应的响应
 */
export class HeartbeatRequest implements GameMessage {
    readonly messageName = "HeartbeatRequest";
}

export class HeartBeat {
    /**
     * 是否启用心跳
     */
    private static heartbeatEnabled = false;

    /**
     * 心跳计数器，每10秒增1，到3则送出心跳，沙雕腾讯需要30秒一跳，我也没办法
     */
    private static heartbeatCounter = 0;

    /**
     * 心跳初始化标记
     */
    private static heartbeatInitialized = false;

    /**
     * 禁止心跳
     */
    static disableHeartbeat() {
        HeartBeat.heartbeatEnabled = false;
        HeartBeat.heartbeatCounter = 0;
    }

    static enableHeartbeat() {
        if (!HeartBeat.heartbeatEnabled) {
            HeartBeat.heartbeatCounter = 0;
            HeartBeat.heartbeatEnabled = true;
        }

        if (!HeartBeat.heartbeatInitialized) {
            HeartBeat.heartbeatInitialized = true;

            (async () => {
                while (true) {
                    await delay(10);
                    try {
                        const session = getCurrentSession();
                        if (HeartBeat.heartbeatEnabled && session.sessionId && session.serialNumber) {
                            if (++HeartBeat.heartbeatCounter >= 3) {
                                HeartBeat.heartbeatCounter = 0;
                                AxiosManager.sendMessage(new HeartbeatRequest());
                            }
                        }
                    } catch (err) {
                        Logger.error(err);
                    }
                }
            })();
        }
    }
}
